<template>
	<view class="pageBox">
		<view class="topTipBox">
			<view class="title">代办说明</view>
			<view class="text">说明：将为广大人才提供代办服务</view>
		</view>
		<view class="gapBox"></view>
		<view class="formBox">
			<u--form labelPosition="left" :model="formData" labelWidth="160rpx" :rules="rules" ref="uForm">
				<view class="formItemBox">
					<u-form-item label="联系人" borderBottom>
						<view class="inputView">
							{{userInfo.nickName}}
						</view>
					</u-form-item>
					<u-form-item label="联系方式" borderBottom>
						<view class="inputView">
							{{userInfo.phonenumber}}
						</view>
					</u-form-item>
					<u-form-item label="代办日期" prop="stayTimer" borderBottom @click="openTime('timeShow','stayTimer')">
						<view class="placeholderText" v-if="!formData.stayTimer">请选择代办日期</view>
						<view class="inputView" v-else>
							{{setWeek(formData.stayTimer)}}
						</view>
					</u-form-item>
					<u-form-item label="代办类型" prop="handleType" borderBottom>
						<view class="inputView" @click="openTime('show','handleType')">
							<view class="placeholderText" v-if="!formData.handleType">请选择代办类型</view>
							<view v-else>{{formData.handleTypeLabel}}</view>
						</view>
					</u-form-item>
					<u-form-item label="代办事项" prop="matter" borderBottom>
						<u--textarea v-model="formData.matter" placeholderClass="plText" placeholder="请输入事项说明"
							autoHeight border="none"></u--textarea>
					</u-form-item>
					<u-form-item label="备注" prop="remark" borderBottom>
						<u--textarea v-model="formData.remark" placeholderClass="plText" placeholder="请输入事项说明"
							autoHeight border="none"></u--textarea>
					</u-form-item>
					<u-form-item label="材料" prop="materials" borderBottom>
						<u-upload width="160rpx" height="160rpx" :fileList="fileList"
							@afterRead="afterRead($event, 'fileList')" @delete="deletePic($event, 'fileList')" multiple
							accept="file">
						</u-upload>
					</u-form-item>

				</view>
				<view class="gapBox"></view>

				<view class="btnBox">
					<view class="btn" @click="submit">提交</view>
				</view>
			</u--form>
			<u-picker :show="show" :columns="[dictList.handle_type]" keyName="label" title="代办类型"
				@confirm="confirmPicker1($event,'show')" @cancel="closePicker('show')"
				@close="closePicker('show')"></u-picker>
			<u-datetime-picker :minDate="-4607395543000" ref="datetimePicker" title="预约时间" :show="timeShow"
				v-model="time" mode="date" :formatter="formatter" @confirm="confirmPicker($event,'timeShow')"
				@cancel="closePicker('timeShow')" @close="closePicker('timeShow')"></u-datetime-picker>
		</view>
	</view>
</template>

<script>
	import {
		formatTime
	} from "@/utils/util.js"
	import * as handleApi from "@/api/serve/handle.js"
	import * as systemApi from "@/api/system.js"
	import * as uploadApi from "@/api/upload.js"
	export default {
		data() {
			return {
				show: false,
				timeShow: false,
				time: Number(new Date()),
				fileList: [],
				fileList_imgs: [],
				fileList_old: [],
				eliteInfo: null,
				userInfo: {
					nickName: '',
					phonenumber: ''
				},
				formData: {
					stayTimer: '',
					handleType: '',
					handleTypeLabel: '',
					matter: '',
					remark: ''
				},
				rules: {
					'stayTimer': {
						type: 'number',
						required: true,
						message: '请选择代办日期',
						trigger: ['blur', 'change']
					},
					'handleType': {
						type: 'string',
						required: true,
						message: '请选择代办类型',
						trigger: ['blur', 'change']
					},
					'materials': {
						type: 'string',
						required: true,
						message: '请上传材料',
						trigger: ['blur', 'change']
					},

				},
				dicts: {
					handle_type: {}
				},
				dictList: {
					handle_type: []
				},
			};
		},
		onReady() {
			// 微信小程序需要用此写法
			this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		onLoad() {
			this.getDictDataList('handle_type')
		},
		onShow() {
			this.userInfo = this.$store.getters.my_userInfo
			this.eliteInfo = this.$store.getters.eliteInfo
			if (!this.userInfo || !this.eliteInfo) {
				this.$store.dispatch('userBaseInfo').then(res => {
					this.userInfo = res.user
					this.eliteInfo = res.eliteInfo
				})
			}
		},
		methods: {
			// 删除图片
			deletePic(event, dataStr) {
				this[dataStr].splice(event.index, 1)
				if (typeof(this[dataStr + '_imgs']) === 'string') {
					this[dataStr + '_imgs'] = ''
				} else {
					this[dataStr + '_imgs'].splice(event.index, 1)
				}
				console.log(this[dataStr + '_imgs'])
			},
			// beforeRead(file, lists) {
			// 	// const {
			// 	// 	name,
			// 	// 	size,
			// 	// 	type
			// 	// } = file
			// 	const imgTypes = ['bmp', 'jpg', 'png', 'jpeg']
			// 	const IMGMaxSize = this.IMGMaxSize
			// 	file.forEach(item => {
			// 		const isJPG = imgTypes.indexOf(item.type) !== -1;
			// 		const sizeT = item.size <= IMGMaxSize
			// 	})
			// 	console.log(file, lists);
			// 	return sizeT && isJPG
			// },
			// 新增图片
			async afterRead(event, dataStr) {
				console.log(event, dataStr)
				const that = this
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				console.log(event.file);
				let lists = [].concat(event.file)
				let fileListLen = this[dataStr].length
				//备份 失败回调
				that[dataStr + '_old'] = JSON.parse(JSON.stringify(that[dataStr]))
				lists.map(item => {
					that[dataStr].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {

					const result = await that
						.uploadFilePromise(lists[i].url, dataStr)
						.then(res => {
							return res
						})
						.catch(() => {
							// that[dataStr] = that[dataStr + '_old']
							return false
						})
					console.log(result);
					if (result) {
						let item = that[dataStr][fileListLen]
						that[dataStr].splice(
							fileListLen,
							1,
							Object.assign(item, {
								status: 'success',
								message: '',
								url: result.url
							})
						)
						fileListLen++
					} else {
						let item = that[dataStr][fileListLen]
						that[dataStr].splice(
							fileListLen,
							1
						)
					}
					console.log(that[dataStr]);
					that[dataStr + '_old'] = JSON.parse(JSON.stringify(that[dataStr]))
				}
			},
			uploadFilePromise(url, dataStr) {
				return new Promise((resolve, reject) => {
					uploadApi
						.upload(url)
						.then((
							data
						) => {
							console.log(data)
							const {
								fileName,
								newFileName,
								originalFilename,
								url
							} = data
							const imgData = {
								fileName,
								newFileName,
								originalFilename,
								url
							}
							if (Object.prototype.toString.call(this[dataStr + '_imgs']) ===
								'[object Array]') {
								this[dataStr + '_imgs'].push(imgData)
							} else if (Object.prototype.toString.call(this[dataStr + '_imgs']) ===
								'[object String]') {
								this[dataStr + '_imgs'] = imgData
							}
							console.log(this[dataStr + '_imgs']);
							resolve(imgData)
						})
						.catch(reject)
				})
			},
			getDictDataList(dictType) {
				return new Promise((resolve, reject) => {
					systemApi.dictDataList(dictType).then(({
						rows
					}) => {
						let objs = {}
						let keyValues = []
						rows.forEach((item) => {
							objs[item.dictValue] = item.dictLabel
							keyValues.push({
								label: item.dictLabel,
								text: item.dictLabel,
								value: item.dictValue
							})
						})
						this.dicts[dictType] = objs
						this.dictList[dictType] = keyValues
						resolve({
							objs,
							keyValues,
							rows
						})
					}).catch(reject)
				})
			},
			confirmPicker1({
				value
			}, showName) {
				const timeName = this.timeName
				this.formData[timeName] = value[0].value
				this.formData[timeName + 'Label'] = value[0].label
				this[showName] = false
			},
			confirmPicker({
				value,
				mode
			}, showName) {
				const timeName = this.timeName
				this.formData[timeName] = value
				this[showName] = false
			},
			closePicker(show) {
				this[show] = false
				this.timeName = ''
			},
			openTime(show, timeName) {
				this[show] = true
				this.timeName = timeName
			},
			closeTime(show, timeName) {
				this[show] = false
				this.timeName = ''
			},
			setWeek(value) {
				const dateTime = formatTime(new Date(value), '-')
				return `${dateTime.time1}`
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			submit() {
				const that = this
				if (this.fileList.length > 0) {
					this.formData.materials = JSON.stringify(this.fileList)
				}
				const formData = JSON.parse(JSON.stringify(this.formData))
				formData.stayTimer = formatTime(formData.stayTimer, "-").time1
				console.log(formData);
				this.$refs.uForm.validate().then(res => {
					uni.$u.throttle(
						handleApi.addhandle(formData).then(res => {
							that.$toast1("提交成功", setTimeout(() => {
								that.$navTo(
									'pages/my/serve/agent/agentList/agentList', {},
									'redirectTo')
							}, 600))
						}), 500)
				}).catch(errors => {
					this.formData.materials = null
				})
			}
		},
	}
</script>

<style lang="scss" scoped>
	@import "@/pages/my/server.scss";

	/deep/.plText {
		font-size: 28rpx;
		color: #979797
	}
</style>